package main

import (
	"fmt"
)

//#link: https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/
func main() {
	node1 := &TreeNode{Val: 2}
	node2 := &TreeNode{Val: 2}
	root := &TreeNode{Val: 2, Left: node1, Right: node2}
	fmt.Println(findSecondMinimumValue(root))
}

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func findSecondMinimumValue(root *TreeNode) int {
	result := 1 << 31
	//根节点肯定是最小的
	if root == nil {
		return -1
	}
	queue := make([]*TreeNode, 0)
	minVal := root.Val
	//若左右节点不相等则返回，否则继续寻找下一层
	queue = append(queue, root)
	for len(queue) > 0 {
		poll := queue[0]
		if poll.Left != nil {
			queue = append(queue, poll.Left)
			queue = append(queue, poll.Right)
		}
		queue = queue[1:]
		if poll.Val > minVal {
			result = min(result, poll.Val)
		}
	}
	if result == 1<<31 {
		result = -1
	}
	return result
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
